package thread;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;


public class Demo56 {
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("请输入目录路径：");
        String n = scanner.next();
        File dir= new File(n);
        if (!dir.isDirectory()) {
            System.out.println("输入错误，请输入目录的路径");
            return;
        }
        System.out.println("请输入关键字：");
        String keyWords = scanner.next();
        scanDir(dir, keyWords);
    }

    private static void scanDir(File dir, String keyWords) {
        //file目录中所有的文件对象或者目录对象
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dealFile(file, keyWords);
            } else {
                scanDir(file, keyWords);
            }
        }
    }

    private static void dealFile(File file, String keyWords) {
        //1.通过文件名进行查找
        if (file.getName().contains(keyWords)) {
            System.out.println("文件名包含关键字："+file.getAbsoluteFile());
            return;
        }
        //2.通过文件中的内容进行查找
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(file)) {
            while (true) {
                char[] bytes = new char[1024];
                int n = reader.read(bytes);
                if (n == -1) {
                    break;
                }
                stringBuilder.append(bytes, 0, n);
            }
            if (stringBuilder.indexOf(keyWords) >= 0) {
                System.out.println("文件内容包含关键字："+file.getAbsoluteFile());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
